package cn.hrc.controller;

import cn.hrc.dao.FileDao;
import cn.hrc.dao.UserDao;
import cn.hrc.entity.LargeFile;
import cn.hrc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/home")
public class LoginController {
    @Autowired
    UserDao userDao;
    @Autowired
    FileDao fileDao;
    /** 去登录 */
    @RequestMapping("/go2login")
    public String go2Longin(){return "login";}
    /** 判断登录 */
    @PostMapping("/login")
    public String login(String phone, String pwd, HttpServletRequest req){
        System.out.println("poone:\t"+phone+"pwd:\t"+pwd);
        HttpSession session = req.getSession();
        System.out.println("Login:\t"+session.getId());
        User user = userDao.findByPhone(phone);
        if (user == null){
            req.setAttribute("loginmsg","账号不存在");
            return "login";
        }
        if (pwd != null && pwd.equals(user.getPwd())){
            user.setPwd("");
            session.setAttribute("who",user);
            req.setAttribute("loginmsg","登录成功");
            return "login";
        }
        req.setAttribute("loginmsg","密码错误");
        return "login";
    }
    /** 退出登录
     * 教师，学生【更改密码退出登录】
     */
    @RequestMapping("/logout")
    public  String logout(HttpSession session, Model model){
        System.out.println("销毁");
        session.invalidate();
        model.addAttribute("loginmsg","请重新登录");
        return "login";
    }
    /** 显示图片【所有有关图片显示的都调用该地址】
     * /home/showImg/ */
    @GetMapping("/showImg/{uuid}")
    public void showImg(@PathVariable("uuid")String uuid,
                        HttpServletResponse resp) throws IOException {
        System.out.println("UUID:\t"+uuid);
        LargeFile one = fileDao.findOne(uuid);
        System.out.println("图片：\t"+one);

        Object content = one.getContent();
        System.out.println("content：\t"+content);

        OutputStream os = resp.getOutputStream();

        resp.setContentType("image/jpeg");

        byte[] buf = (byte[]) content;
        os.write(buf);
        os.flush();
    }

}
